package com.xoa.controller.budget;

import com.alibaba.fastjson.JSONObject;
import com.xoa.controller.enclosure.EnclosureController;
import com.xoa.dao.users.OrgManageMapper;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.OrgManage;
import com.xoa.service.budget.BudgetEnclosureService;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.util.Constant;
import com.xoa.util.ToJson;
import com.xoa.util.common.MobileCheck;
import com.xoa.util.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * Created by Administrator on 2019/6/17.
 */
@Controller
public class BudgetEnclosureController {

    private Logger loger = LoggerFactory.getLogger(EnclosureController.class);

    @Autowired
    private BudgetEnclosureService budgetEnclosureService;

    @Autowired
    private EnclosureService enclosureService;

    @Autowired
    private OrgManageMapper orgManageMapper;


    @RequestMapping(value = "/budgetUpload", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    void upload(@RequestParam("file") MultipartFile[] files, String module,
                @RequestParam(value = "company", required = false) String company,
                @RequestParam(value = "flag", required = false) String flag, HttpServletRequest request, HttpServletResponse response) {
        ToJson<Attachment> json = new ToJson<Attachment>(0, null);


        StringBuffer sb = new StringBuffer();
        if (StringUtils.checkNull(company)) {
            company = (String) request.getSession().getAttribute(
                    "loginDateSouse");
            if (StringUtils.checkNull(company)){
                List<OrgManage> org=orgManageMapper.queryId();
                if (org!=null&&org.size()>0){
                    company = org.get(0).getOid().toString().trim();
                }
                sb.append("xoa"+company);
            }else {
                sb.append("xoa" + (String) request.getSession().getAttribute(
                        "loginDateSouse"));
            }
        } else {
            sb.append(company);
        }
        try {
          /*  System.setProperty("sun.jnu.encoding","UTF-8");
            System.setProperty("file.encoding","UTF-8");*/
            boolean a = false;
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                if (file.getSize() == 0) {
                    a=true;
                }
            }
            if (a){
                json.setFlag(1);
                json.setMsg("The file size is 0");
            }else {
                List<Attachment> list = new ArrayList<>();
                // 传入flag时，走预算管理专用上传接口
                list = budgetEnclosureService.budgetUpload(files, sb.toString(), module, flag);
                json.setObj(list);
                json.setMsg("OK");
                json.setFlag(0);
            }

            response.setHeader("content-type", "text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream out = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(out,"UTF-8");

            ow.write(JSONObject.toJSONString(json));
            ow.flush();
            ow.close();
            //response.setContentType("application/json");
            //writer(response, JSONObject.toJSONString(json));
        } catch (Exception e) {
            json.setMsg(e.getMessage());
        }
        return;
    }


    @RequestMapping(value = "/budgetDownload")
    public String download(@RequestParam("AID") int aid,
                           @RequestParam("MODULE") String module,
                           @RequestParam("YM") String ym,
                           @RequestParam("ATTACHMENT_ID") String attachmentId,
                           //@RequestParam(value = "ATTACHMENT_NAME",required = false) String attachmentName ,
                           @RequestParam("COMPANY") String company,
                           String isOld,
                           HttpServletResponse response,
                           HttpServletRequest request) throws Exception {
        if (StringUtils.checkNull(company)){
            company="xoa1001";
        }
        String attachmentName = "";
        System.setProperty("sun.jnu.encoding","UTF-8");
        System.setProperty("file.encoding","UTF-8");

        if( aid != 0 ){
            Attachment attachment =  enclosureService.selectByAid(aid);
            if(attachment !=null){
                attachmentName = attachment.getAttachName();
            }

        }else{
            String attachmentName1 = request.getParameter("ATTACHMENT_NAME");
            String aName = "";
            if (attachmentName1.substring(attachmentName1.length() - 1, attachmentName1.length()).equals("*")) {
                aName = attachmentName1.substring(0, request.getParameter("ATTACHMENT_NAME").length() - 1);
            } else {
                aName = attachmentName1;
            }
            attachmentName = URLDecoder.decode(aName, "UTF-8");
        }



        //读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                sb = sb.append(str2 +"/xoa");
            }
            sb.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            sb=sb.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
        if (StringUtils.checkNull(sb.toString())) {
            String a = request.getRealPath("");
            sb.append(a);
            sb.append(System.getProperty("file.separator")).
//                    append("attach").
//                    append(System.getProperty("file.separator")).
        append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym).
                    append(System.getProperty("file.separator")).append(attachmentId).append(".").append(attachmentName);
        } else if (attachmentName.contains("预算附件") || attachmentName.substring(0,3).equals("合同-") || attachmentName.substring(0,5).equals("会议纪要-")
                || attachmentName.substring(0,5).equals("公共附件-")) {
            sb.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym).
                    append(System.getProperty("file.separator")).append(attachmentId).append(".").append(attachmentName);
        }  else {
            sb.append(System.getProperty("file.separator")).
//                    append("attach").
//                    append(System.getProperty("file.separator")).
        append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym).

                    append(System.getProperty("file.separator")).append(attachmentId).append(".").append(attachmentName);
        }
        String path = sb.toString();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        String userAgent = request.getHeader("User-Agent").toUpperCase();
        if (!MobileCheck.isMobileDevice(userAgent)) {
            /*byte[] bytes = userAgent.contains("MSIE") ? attachmentName.getBytes()
                    : attachmentName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
            attachmentName = new String(bytes, "ISO-8859-1");*/

            if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") || userAgent.contains("EDGE")) {
                attachmentName = URLEncoder.encode(attachmentName, "utf-8");
                attachmentName = attachmentName.replace("+", "%20");    //IE下载文件名空格变+号问题
            } else {
                attachmentName = new String(attachmentName.getBytes("UTF-8"), "ISO-8859-1");
            }

        }else {
            if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") || userAgent.contains("EDGE")) {
                attachmentName = URLEncoder.encode(attachmentName, "utf-8");
                attachmentName = attachmentName.replace("+", "%20");    //IE下载文件名空格变+号问题
            } else {
                attachmentName = new String(attachmentName.getBytes("UTF-8"), "ISO-8859-1");
            }
        }

        response.setHeader("Content-disposition",
                String.format("attachment; filename=\"%s\"", attachmentName));

        InputStream inputStream = null;
        OutputStream os = null;
        try {
            File file = new File(path);
            // 如果文件不存在
            if (!file.exists()) {
                path = path.replace(attachmentId+".","");
                File file2 = new File(path);
                if(file2.exists()){
                    file = file2;
                }else{
                    request.setAttribute("message", Constant.exesit);
                    return Constant.exesit.toString();
                }
            }
            inputStream = new FileInputStream(new File(path));
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 这里主要关闭。
            if (os != null) {
                os.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return null;
    }


    @RequestMapping(value = {"/budgetDelete"}, method = {RequestMethod.GET}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson delete(@RequestParam("AID") String aid,
                         @RequestParam("MODULE") String module,
                         @RequestParam("YM") String ym,
                         @RequestParam("ATTACHMENT_ID") String attachmentId,
                         @RequestParam("ATTACHMENT_NAME") String attachmentName,
                         @RequestParam("COMPANY") String company,
                         HttpServletResponse response,
                         HttpServletRequest request) {
        return budgetEnclosureService.delete(aid, module, ym, attachmentId, attachmentName, company, response, request);
    }
}
